(function (angular) {
  'use strict';
  angular
    .module('fs.ajax', ['ngResource', 'fs.logger', 'fs.storage'])
    .config([
      '$resourceProvider',
      function ($resourceProvider) {
        $resourceProvider.stripTrailingSlashes = false;
      }
    ])
    .provider('ajaxServiceFactory', function () {
      var provider = this;
      provider.baseUrl = '';
      provider.params = {};
      provider.setBaseUrl = function (url) {
        provider.baseUrl = url;
      };
      provider.setDefaultParmas = function (params) {
        provider.params = params;
      };
      provider.$get = [
        '$resource',
        '$q',
        '$timeout',
        'loggerFactory',
        'storageService',
        '$parse',
        function ($resource, $q, $timeout, loggerFactory, storageService, $parse) {

          var log = loggerFactory.getLogger('ajaxServiceFactory');
          return {
            buildAjaxService: buildAjaxService,
            setBaseUrl: provider.setBaseUrl,
            setDefaultParmas: provider.setDefaultParmas
          };

          function buildAjaxService(configs) {
            var services = {}, serviceConfig;
            angular.forEach(configs, function (config, key) {
              if (provider.baseUrl && config.url) {
                config.url = provider.baseUrl + config.url;
              }
            });
            services = $resource(provider.baseUrl, provider.params, configs);
            return createProxyService(configs, services);
          }
          function createProxyService(configs, services) {
            var proxyService = {};
            angular.forEach(configs, function (config, key) {
              proxyService[key] = function (params) {
                var deferred = $q.defer();
                if (params && params.$type == "SearchCriteria" && params.storageSearchCriteria == true) {
                  storageService.saveSearchCriteria(params);
                }
                return sendRequest(config, services[key], params);
              };
            });
            return proxyService;
          }

          function sendRequest(config, service, params) {
            var deferred = $q.defer();
            try {
              params = angular.copy(params);
            } catch (e) {
              log.debug('can not copy the params:' + params);
              deferred.reject(e);
            }
            service(params, function (response) {
              deferred.resolve({
                data: response ? response.data : response
              });
            }, function (error) {
              deferred.reject(error);
            });
            return deferred.promise;
          }

        }
      ];
    });
})(angular);
